package com.xomily.web.controller.system;

import com.xomily.common.annotation.Log;
import com.xomily.common.core.controller.BaseController;
import com.xomily.common.core.domain.AjaxResult;
import com.xomily.common.core.domain.entity.SysUser;
import com.xomily.common.core.page.TableDataInfo;
import com.xomily.common.enums.BusinessType;
import com.xomily.common.utils.poi.ExcelUtil;
import com.xomily.system.domain.SysMessage;
import com.xomily.system.service.ISysMessageService;
import com.xomily.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;


/**
 * 留言Controller
 *
 * @author ruoyi
 * @date 2025-04-05
 */
@RestController
@RequestMapping("/system/message")
public class SysMessageController extends BaseController {
    @Autowired
    private ISysMessageService sysMessageService;
    @Autowired
    private ISysUserService iSysUserService;

    /**
     * 查询留言列表
     */
    @PreAuthorize("@ss.hasPermi('system:message:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysMessage sysMessage) {
        startPage();
        // 检查并获取消息列表
        List<SysMessage> messageList = Optional.ofNullable(sysMessageService.selectSysMessageList(sysMessage))
                .orElse(Collections.emptyList());

        // 检查并构建用户ID到昵称的映射
        Map<Long, String> userMap = Optional.ofNullable(iSysUserService.selectUserList(new SysUser()))
                .orElse(Collections.emptyList())
                .stream()
                .collect(Collectors.toMap(
                        SysUser::getUserId,
                        SysUser::getNickName,
                        (existing, replacement) -> existing // 处理重复键的情况
                ));

        // 更新消息列表中的用户名
        messageList.forEach(item -> {
            String nickName = userMap.getOrDefault(item.getUserId(), "未知用户"); // 提供默认值避免空指针
            item.setUserName(nickName + " (" + item.getUserId() + ")");
        });

        return getDataTable(messageList);
    }

    /**
     * 导出留言列表
     */
    @PreAuthorize("@ss.hasPermi('system:message:export')")
    @Log(title = "留言", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysMessage sysMessage) throws IOException {
        List<SysMessage> list = sysMessageService.selectSysMessageList(sysMessage);
        ExcelUtil<SysMessage> util = new ExcelUtil<SysMessage>(SysMessage.class);
        util.exportExcel(response, list, "留言数据");
    }

    /**
     * 获取留言详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:message:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(sysMessageService.selectSysMessageById(id));
    }

    /**
     * 新增留言
     */
    @PreAuthorize("@ss.hasPermi('system:message:add')")
    @Log(title = "留言", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysMessage sysMessage) {
        AjaxResult user = getUser(sysMessage);
        if (user != null) return user;
        return toAjax(sysMessageService.insertSysMessage(sysMessage));
    }

    private AjaxResult getUser(SysMessage sysMessage) {
        SysUser sysUser = iSysUserService.selectUserById(sysMessage.getUserId());
        if (sysUser == null) {
            return AjaxResult.error("用户不存在");
        }
        return null;
    }

    /**
     * 修改留言
     */
    @PreAuthorize("@ss.hasPermi('system:message:edit')")
    @Log(title = "留言", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysMessage sysMessage) {
        AjaxResult user = getUser(sysMessage);
        if (user != null) return user;
        return toAjax(sysMessageService.updateSysMessage(sysMessage));
    }

    /**
     * 删除留言
     */
    @PreAuthorize("@ss.hasPermi('system:message:remove')")
    @Log(title = "留言", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(sysMessageService.deleteSysMessageByIds(ids));
    }
}
